package util;

import java.io.BufferedWriter;
import java.io.IOException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import protocal.DataPackage;
import client.ChatClient;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MessageSender {
	private final static Logger logger = LogManager.getLogger(MessageSender.class); 
	private static ObjectMapper mapper;
	static{
		mapper = new ObjectMapper();
	}
	
	public static void send(DataPackage dataPackage){
		try {
			BufferedWriter writer = ChatClient.getInstance().getWriter();
			String data = mapper.writeValueAsString(dataPackage)+"\n";
			logger.info(data);
			writer.write(data);
			writer.flush();
		} catch (JsonProcessingException e) {
			logger.error(e);
		} catch (IOException e) {
			logger.error(e);
		}
		
	}
	
	public static void send(DataPackage dataPackage,BufferedWriter writer){
		try {
			String data = mapper.writeValueAsString(dataPackage)+"\n";
			logger.info(data);
			writer.write(data);
			writer.flush();
		} catch (JsonProcessingException e) {
			logger.error(e);
		} catch (IOException e) {
			logger.error(e);
		}
		
	}

}
